package com.cn.fenyu.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.cn.fenyu.bean.active_info;
import com.cn.fenyu.bean.student_info;
import com.cn.fenyu.bean.update_info;
import com.cn.fenyu.pack.Https_link3;
import com.cn.fenyu.servies.MainServies;

import com.vaptcha.*;

@Controller
public class MainController {

	@Autowired
	private MainServies service;

	// @RequestMapping("index")
	// public String index() {
	// return "index";
	// }
	//
	// @RequestMapping("loginpage")
	// public String loginpage() {
	// return "loginpage";
	// }
	//
	// @RequestMapping("show")
	// public String show() {
	// return "show";
	// }
	//
	// @RequestMapping("uploadpage")
	// public ModelAndView uploadpage(HttpSession session) {
	// student_info stu = (session.getAttribute("user") != null ? ((student_info)
	// session.getAttribute("user"))
	// : null);
	// ModelAndView mv = new ModelAndView();
	// if (stu != null) {
	// mv.setViewName("upload");
	// } else {
	// mv.setViewName("index");
	// }
	// return mv;
	// }

	@RequestMapping(value = "changepassword", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String changepass(@RequestParam("old") String userpass, @RequestParam("new") String newuserpass,
			HttpSession session) {
		JSONObject obj = new JSONObject();
		student_info stu = (student_info) session.getAttribute("user");
		if (stu != null) {
			// if (!LoginListen.loginlist.contains(stu)) {
			if (stu.getStudentpw().equals(userpass)) {
				stu.setStudentpw(newuserpass);
				service.updateuser(stu);
				obj.put("success", 1);
			} else {
				obj.put("success", 0);
				obj.put("message", "密码错误");
			}
		} else {
			obj.put("success", 0);
			obj.put("message", "没有匹配到此用户");
		}
		return obj.toJSONString();
	}

	@RequestMapping(value = "usershow", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String usershow(@RequestParam("userid") String userid) {
		if (service.finduser(userid) != null) {
			List<update_info> list = service.sublistbyuser(userid);
			List<active_info> aclist = service.activelist();
			List<JSONObject> linkd = new ArrayList<JSONObject>();
			for (update_info update : list) {
				JSONObject obj = new JSONObject();
				obj.put("atype", "");
				for (int i = 0; i < aclist.size(); i++) {
					if (update.getActiveId() == aclist.get(i).getIdtype())
						obj.put("atype", aclist.get(i).getName());
				}
				List<String> mem = JSON.parseArray(update.getGroupJson(), String.class);
				JSONArray arrmem = new JSONArray();
				arrmem.add(service.finduser(update.getLeader()).getStudentname());
				for (String id : mem) {
					student_info stus = service.finduser(id);
					if (stus != null)
						arrmem.add(stus.getStudentname());
				}
				obj.put("author", arrmem);
				obj.put("url", "web" + update.getPath());
				obj.put("uptime", update.getTime());
				linkd.add(obj);
			}
			JSONObject obj = new JSONObject();
			obj.put("success", 1);
			obj.put("data", linkd);
			return obj.toJSONString();
		} else {
			JSONObject obj = new JSONObject();
			obj.put("success", 0);
			obj.put("message", "没有匹配到此用户");
			return obj.toJSONString();
		}

	}

	@RequestMapping(value = "indexshow", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String indexshow(@RequestParam(value = "page", required = false) Integer page) {
		List<update_info> uplist = service.selectall();
		List<active_info> aclist = service.activelist();
		JSONArray arrdata = new JSONArray();
		if (page == null || page == 0)
			page = 1;
		for (int j = (page - 1) * 9; j < uplist.size() && j < (page - 1) * 9 + 9; j++) {
			JSONObject data = new JSONObject();
			data.put("atype", "");
			for (int i = 0; i < aclist.size(); i++) {
				if (uplist.get(j).getActiveId() == aclist.get(i).getIdtype())
					data.put("atype", aclist.get(i).getName());
			}
			List<String> mem = JSON.parseArray(uplist.get(j).getGroupJson(), String.class);
			JSONArray arrmem = new JSONArray();
			arrmem.add(service.finduser(uplist.get(j).getLeader()).getStudentname());
			for (String id : mem) {
				student_info stus = service.finduser(id);
				if (stus != null)
					arrmem.add(stus.getStudentname());
			}
			data.put("author", arrmem);
			data.put("url", "web" + uplist.get(j).getPath());
			data.put("uptime", uplist.get(j).getTime());

			arrdata.add(data);
		}

		JSONObject obj = new JSONObject();
		obj.put("success", 1);
		obj.put("data", arrdata);
		return obj.toJSONString();

	}

	@RequestMapping(value = "dologin", produces = "application/text;charset=UTF-8")
	@ResponseBody
	public String login(@RequestParam("userid") String userid, @RequestParam("userpass") String userpass,
			@RequestParam("response") String responseval, HttpSession session) {
		JSONObject obj = new JSONObject();
		String val;
		try {
			/**
			 * google code key
			 */
			val = new String(
					Https_link3.post("https://recaptcha.net/recaptcha/api/siteverify",
							"secret=***&&response=" + responseval, "utf-8"),
					"utf-8");
			JSONObject encode = JSON.parseObject(val);
			String success = encode.getString("success");
			if (success == "true") {
				student_info stu = service.finduser(userid);
				if (stu != null) {
					// if (!LoginListen.loginlist.contains(stu)) {
					if (stu.getStudentpw().equals(userpass)) {
						JSONObject data = new JSONObject();
						data.put("name", stu.getStudentname());
						obj.put("success", 1);
						obj.put("data", data);
						session.setAttribute("user", stu);
						// LoginListen.loginlist.add(stu);
						return obj.toJSONString();
					} else {
						obj.put("success", 0);
						obj.put("message", "密码错误");
						return obj.toJSONString();
					}
					// } else {
					// obj.put("success", 0);
					// obj.put("message", "账号已经被登陆");
					// return obj.toJSONString();
					// }
				} else {
					obj.put("success", 0);
					obj.put("message", "未找到账户");
					return obj.toJSONString();
				}
			} else {
				obj.put("success", 0);
				obj.put("message", "验证失败");
				return obj.toJSONString();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			obj.put("success", 0);
			obj.put("message", "验证失败");
			return obj.toJSONString();
		}

	}

	@RequestMapping(value = "haslogin", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String haslogin(HttpSession session) {
		student_info stu = (student_info) session.getAttribute("user");
		JSONObject obj = new JSONObject();
		if (stu != null) {
			JSONObject data = new JSONObject();
			data.put("haslogin", true);
			data.put("name", stu.getStudentname());
			obj.put("success", 1);
			obj.put("data", data);
		} else {
			JSONObject data = new JSONObject();
			data.put("haslogin", false);
			obj.put("success", 1);
			obj.put("data", data);
		}
		return obj.toJSONString();
	}

	@RequestMapping(value = "getname", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getnickname(@RequestParam("userid") String userid) {
		student_info stu = service.finduser(userid);
		JSONObject obj = new JSONObject();
		if (stu != null) {
			JSONObject obj2 = new JSONObject();
			obj2.put("id", stu.getStudentid());
			obj2.put("name", stu.getStudentname());
			obj.put("success", 1);
			obj.put("data", obj2);
		} else {
			obj.put("success", 0);
			obj.put("message", "未查询到用户");
		}
		return obj.toJSONString();
	}

	@RequestMapping(value = "cansubmit", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String cansubmit(HttpSession session) {
		JSONObject obj = new JSONObject();
		student_info stu = (session.getAttribute("user") != null ? ((student_info) session.getAttribute("user"))
				: null);
		if (stu != null) {
			List<active_info> aclist = service.activelist();
			/**
			 * version 0.0.2 beta 允许重复提交 注释此处过滤代码 更新日期 update_time:2018-3-27 by 纷羽
			 */
			// List<update_info> up = service.sublistbyuser(stu.getStudentid());
			// ArrayList<active_info> removelist = new ArrayList<active_info>();
			// for (int i = 0; i < aclist.size(); i++) {
			// for (update_info update_info : up) {
			// if (update_info.getActiveId() == aclist.get(i).getIdtype()) {
			// removelist.add(aclist.get(i));
			// }
			// }
			// }
			// for (active_info active_info : removelist) {
			// aclist.remove(active_info);
			// }
			JSONArray arr = new JSONArray();
			for (active_info active_info : aclist) {
				JSONObject objac = new JSONObject();
				objac.put("type", active_info.getIdtype());
				objac.put("name", active_info.getName());
				arr.add(objac);
			}
			obj.put("success", 1);
			obj.put("data", arr);
			return obj.toJSONString();
		} else {
			obj.put("success", 0);
			obj.put("message", "请先登陆");
			return obj.toJSONString();
		}
	}

	@RequestMapping(value = "upload", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer id,
			@RequestParam("list") String list, HttpSession session) {
		student_info stu = (student_info) session.getAttribute("user");
		JSONObject obj = new JSONObject();
		if (stu == null) {
			obj.put("success", 0);
			obj.put("message", "请先登陆");
			return obj.toJSONString();
		} else if (file != null) {
			String packageName = file.getOriginalFilename();
			String type = packageName.substring(packageName.lastIndexOf(".") + 1, packageName.length()).toLowerCase();
			if (!type.equals("zip")) {
				obj.put("success", 0);
				obj.put("message", "请上传zip格式文件");
				return obj.toJSONString();
			} else {
				List<String> user = JSON.parseArray(list, String.class);
				if (user.size() > 9) {
					obj.put("success", 0);
					obj.put("message", "队伍成员数量超过要求");
					return obj.toJSONString();
				}
				for (String string : user) {
					if (service.finduser(string) == null) {
						obj.put("success", 0);
						obj.put("message", "没有找到队员 " + string + " 的相关资料，请核对队员信息");
						return obj.toJSONString();
					}
				}
				String patha = "/" + stu.getStudentid() + "/" + id + "/";
				File path = new File(session.getServletContext().getRealPath("/web" + patha));
				if (path.exists()) {
					/**
					 * 更新此处用于清空文件目录
					 */
					System.gc();
					File[] children = path.listFiles();
					for (int i = 0; i < children.length; i++) {
						children[i].delete();
					}

				}
				File f = new File(session.getServletContext().getRealPath("/web" + patha) + "upload.zip");
				if (!f.getParentFile().exists())
					f.getParentFile().mkdirs();
				try {
					file.transferTo(f);
					System.out.println("outputfile by" + stu.getStudentname() + "as type" + id);
				} catch (IllegalStateException e1) {
					obj.put("success", 0);
					obj.put("message", "文件在上传中出错，请稍后重试");
					e1.printStackTrace();
					return obj.toJSONString();
				} catch (IOException e1) {
					obj.put("success", 0);
					obj.put("message", "文件在上传中出错，请稍后重试");
					e1.printStackTrace();
					return obj.toJSONString();
				}
				try {
					unZipFiles(f, session.getServletContext().getRealPath("/web" + patha), stu.getStudentname());
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					String timestring = format.format(new Date());
					service.submitdel(stu.getStudentid(), id);
					for (String student_info : user) {
						if (student_info.equals(stu.getStudentid()))
							continue;
						update_info up = new update_info();
						up.setPath(patha);
						up.setActiveId(id);
						up.setStuId(student_info);
						up.setLeader(stu.getStudentid());
						up.setGroupJson(JSON.toJSONString(user));
						up.setTime(timestring);
						service.insertUpdate(up);
					}
					update_info up = new update_info();
					up.setPath(patha);
					up.setActiveId(id);
					up.setStuId(stu.getStudentid());
					up.setLeader(stu.getStudentid());
					up.setGroupJson(JSON.toJSONString(user));
					up.setTime(timestring);
					service.insertUpdate(up);
					obj.put("success", 1);
					JSONObject datas = new JSONObject();
					datas.put("url", "/web" + patha);
					obj.put("data", datas);
					return obj.toJSONString();
				} catch (IllegalStateException e) {
					obj.put("success", 0);
					obj.put("message", "文件在保存或解压的过程中出错，请联系管理员");
					f.delete();
					System.err.println(e.toString());
					return obj.toJSONString();
				} catch (IOException e) {
					System.err.println(e.toString());
					obj.put("success", 0);
					obj.put("message", "文件在保存或解压的过程中出错，请联系管理员");
					f.delete();
					return obj.toJSONString();
				}
			}
		} else {
			obj.put("success", 0);
			obj.put("message", "请上传文件");
			return obj.toJSONString();
		}
	}

	/**
	 * 解压工具： 解压文件到指定目录 解压后的文件名，和之前一致
	 * 
	 * @param zipFile
	 *            待解压的zip文件
	 * @param descDir
	 *            指定目录
	 */
	public static void unZipFiles(File zipFile, String descDir, String stuname) throws IOException {

		ZipFile zip = new ZipFile(zipFile);
		String name = zip.getName().substring(zip.getName().lastIndexOf('\\') + 1, zip.getName().lastIndexOf('.'));
		System.out.println(name);
//		File pathFile = new File(descDir);
//		if (!pathFile.exists()) {
//			pathFile.mkdirs();
//		}

		for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");

			// 判断路径是否存在,不存在则创建文件路径
			System.out.println("outputfile by" + stuname + " is :" + outPath);
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			} else {
				String type = outPath.substring(zipEntryName.lastIndexOf(".") + 1, zipEntryName.length()).toLowerCase();
				if (type.equals("jsp"))
					continue;
			}
			// 输出文件路径信息
			// System.out.println(outPath);
			FileOutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		return;
	}

	public static int deletepath(File f) {
		if (!f.exists())
			return 0;
		else if (!f.isDirectory()) {
			f.delete();
			return 1;
		} else {
			int k = 0;
			File[] f2 = f.listFiles();
			for (int i = 0; i < f2.length; i++) {
				if (f2[i].isDirectory()) {
					k += deletepath(f2[i]);
					f2[i].delete();
				} else {
					f2[i].delete();
					k += 1;
				}
			}
			return k;
		}
	}

}
